﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using pwblog.Entities;

namespace pwblog.DataAccess
{
    public class MenuDao
    {
        ManageBlogDataContext dataContext;

        public MenuDao()
        {
            dataContext = new ManageBlogDataContext();
        }

        /// <summary>
        /// lấy danh sách menu
        /// </summary>
        /// <returns></returns>
        public Menu[] GetMenus()
        {
            return dataContext.Menus.ToArray();
        }

        /// <summary>
        /// Lấy danh sách menu theo parent id
        /// </summary>
        /// <param name="parent">ID của menu cha</param>
        /// <returns></returns>
        internal Menu[] GetMenusByParentId(int parent)
        {
            return dataContext.Menus.Where(item => item.Parent == parent).ToArray();
        }

        internal Menu GetMenuById(int id)
        {
            return dataContext.Menus.Where(item => item.id == id).ToArray().First();
        }

        /// <summary>
        /// Thêm menu vào csdl
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        internal int InsertMenu(Menu menu)
        {
            dataContext.Menus.InsertOnSubmit(menu);
            dataContext.SubmitChanges();
            var temp = dataContext.Menus.ToArray();
            return temp.Last().id;
        }

        /// <summary>
        /// cập nhật menu
        /// </summary>
        /// <param name=" newMenu"></param>
        public void UpdateMenu(Menu newMenu)
        {
            var oldMenu = dataContext.Menus.Single(item => item.id == newMenu.id);
            oldMenu.id = newMenu.id;
            oldMenu.MenuTitle = newMenu.MenuTitle;
            oldMenu.MenuUrl = newMenu.MenuUrl;
            oldMenu.Parent = newMenu.Parent;
            oldMenu.SortOrder = newMenu.SortOrder;
            dataContext.SubmitChanges();
        }

        /// <summary>
        /// Xóa đi 1 menu
        /// </summary>
        /// <param name="menu"></param>
        public void DeleteMenu(Menu menu)
        {
            dataContext.Menus.DeleteOnSubmit(menu);
            dataContext.SubmitChanges();
        }
    }
}